package com.concurrent.demo;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @Date 2020/7/13 10:20
 * @Author admin
 * @Description
 */
public class CASDemo {
    //内存值
    volatile int oldValue ;

    int newValue;
    void addOne(){
       do{
           //CAS的自旋每次都读取新的值才有意义，不然就拿老的值去CAS，万一被其他线程修改了，那将一直自旋，并毫无意义
           //int oldValue = getValue();
           newValue = oldValue +1;
       }while (newValue!=cas(oldValue,newValue));
    }
    synchronized int cas(int expect,int newValue){
        int count = oldValue;//读取内存值
        if(expect == oldValue){//如果期望值等于内存值,则将内存值更新为新值
            oldValue = newValue;
        }

        return count;//返回旧值
    }

    public static void main(String[] args) {

    }


}
